package com.kafka.model;

import com.kafka.logs.SystemLogger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName TcpServer
 * @Description netty服务启动类
 * @Author Jesson
 * @Date 2019/1/15 9:46
 * @Version 1.0
 **/
public class TcpServer extends Thread {
    private ServerBootstrap bootstrap;
    private TcpServerConfig serverConfig;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    /**
     * 映射网络套接字
     */
    private static ConcurrentHashMap<String, Channel> channelMap = new ConcurrentHashMap<>();
    public TcpServer(TcpServerConfig serverConfig) {
        this.serverConfig = serverConfig;
    }
    public static ConcurrentHashMap<String, Channel> getChannelMap(){
        return channelMap;
    }
    @Override
    public void run(){
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try {
            bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new TcpServerFactory(serverConfig,channelMap))
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            /**启动服务器*/
            ChannelFuture future = bootstrap.bind(serverConfig.getPort()).sync();
            System.out.println("network service started successfully");
            SystemLogger.info("network service started successfully");
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            System.out.println("network service failed to start,exception = " +e);
            SystemLogger.error("network service failed to start,exception = {}", e);
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            System.exit(1);
        }
    }
}
